<template>
  <view class='analyze_page' :class='{top:search_status}'>
    <loading :status='load_status'></loading>
    <view class='search_view' :class='{show_search:search_status}'>
      <view class='input_item'>
        <view>
          <text class='iconfont icon-sousuo'></text>
        </view>
        <input type="text" placeholder="请输入报告名称关键词搜索" v-model.trim="keyWord" @confirm='confirmSearch'>
      </view>
    </view>

    <view class='analyze_list'>
      <view v-for='(item,index) in list' :key='index'>
        <analyze-item
          :content="item"
          @clickLeftBtn="updateReport(item,index)"
          @clickRightBtn="getHistoryList(item.parentEventId,index)"
          @delete="deleteAnalyze(item.parentEventId,item.reportName,index)"
        ></analyze-item>
      </view>
    </view>
    <hint :status='hint_status'></hint>

    <popup ref='analyze_popup'>
      <view class='hotList_set'>
        <view class='set_title'>
          <text v-if='history_list.length != 0'>{{history_list[0].eventName}}</text>
          <!-- 更新按钮 弃用 -->
          <view class='update_btn' hover-class='btn_hover2' @tap='updateReport' v-if="false">更新</view>
        </view>
        <scroll-view :scroll-y='true' class='set_list'>
            <analyze-item
              :content2="history_list"
              :title_show="false"
              :left_btn_text="'查看'"
              :right_btn_text="'删除'"
              @clickLeftBtn="lookAnalyze"
              @clickRightBtn="deleteAnalyze"
            ></analyze-item>
        </scroll-view>
        <view class='btn_box'>
          <button class='btn' @tap='closePopup'>关闭</button>
          <button class='btn del_btn' @tap='deleteAnalyze(event_id,history_list[0].eventName,report_index)'>删除报告</button>
        </view>
      </view>
    </popup>

    <!-- 日期选择器 -->
    <datepicker 
      :show='picker_show'
      @confirm='confirmDate'
      @cancel='closePicker'></datepicker>
  </view>
</template>

<script>

  import analyzeItem from './components/analyzeItem.vue'
  import datepicker from '@/pages/common/datepicker.vue'

  export default {
    components: {
      analyzeItem,
      datepicker
    },
    data() {
      return {
        //#ifdef H5
        head_top: 44,
        //#endif
        //#ifdef APP-PLUS
        head_top: 0,
        //#endif
        search_status: false,
        picker_show: false,
        date_arr: ["",""],       // 时间范围
        keyWord: "",
        page: 1,
        num: 5,
        total: 0,
        list: [],
        hint_status: 0,
        load_status: 0,
        history_list: [],
        event_id: "",
        report_index: null
      }
    },
    watch: {
      keyWord(val) {
        if(val == "") {
          this.initGetData()
        }
      }
    },
    // 点击搜索、添加图标
    onNavigationBarButtonTap(e){
      if(e.float == "right") {
        if(!this.search_status) {
          this.search_status = true;
        }else {
          this.closeSearch()
        }
      }
    },
    // 下拉刷新
    onPullDownRefresh() {
      this.load_status = 1;
      this.initGetData();
    },
    // 滚动到底部
    onReachBottom() {
      if(this.list.length >= this.total) {
        this.hint_status = 2;
        return
      }
      this.page++;
      this.getData();
    },
    onReady() {
      let self = this;
      uni.getStorage({
          key: 'report',
          success(res) {
              self.load_status = 1;
              self.list = res.data;
              self.getData()
          },
          fail() {
            self.load_status = 1;
            self.getData()
          }
      });
      
    },
    methods: {
      // 获取列表数据
      getData() {
        this.hint_status = 1;
        this.$http({
          url: this.$api.analyze.list,
          data: {
            pageIndex: this.page,
            pageSize: this.num,
            keyWord: this.keyWord,
          }
        }).then(res => {
          uni.stopPullDownRefresh();
          if(res.code == 0) {
            this.load_status = 2;
            if(this.page == 1){
              this.list = [];
            }
            this.total = res.data.total;
            res.data.list.forEach(val => {
              this.list.push(val)
            })

            if(this.list.length == 0) {
              this.hint_status = 0
            }else {
              if(this.list.length == this.total) {
                this.hint_status = 2
              }
            }
            if(this.page == 1) {
              uni.setStorage({
                key: 'report',
                data: res.data.list
              });
            }
          }else {
            this.load_status = 3;
            uni.stopPullDownRefresh();
          }
        }).catch(err => {
          
          if(err.errMsg == "request:fail timeout") {
              this.hint_status = 3;
              this.load_status = 4;
          }else {
            this.hint_status = 3;
          }
          uni.stopPullDownRefresh();
          
        })
      },
      // 获取历史分析
      getHistoryList(eventId,index) {
        this.event_id = eventId;
        this.report_index = index;
        this.$http({
          url: this.$api.analyze.history,
          data: { eventId }
        }).then(res => {
          if(res.code == 0) {
            this.history_list = res.data.list;
            if(res.data.total > 0) {
              this.$nextTick(() => {
                this.$refs.analyze_popup.show();
              })
            }else {
              uni.showToast({
                  title: '没有可查看的历史',
                  icon: "none"
              });
            }
          }
        })
      },
      // 更新分析报告
      updateAnalyze(date) {
        this.$http({
          url: this.$api.analyze.update,
          data: { 
            eventId: this.event_id,
            startTime: date[0],
            endTime: date[1]
          }
        }).then(res => {
          if(res.code == 0) {
            uni.showToast({
              title: '已提交更新',
              icon: "success"
            });

            let report = {
              reportName: res.data.eventName,
              parentEventId: res.data.parentEventId,
              result: [
                {
                  startTime: res.data.startTime,
                  endTime: res.data.endTime,
                  eventId: res.data.eventId,
                  version: res.data.version,
                  updateOn: res.data.updateOn,
                  status: res.data.status,
                }
              ],
            }
            this.$set(this.list,this.report_index,report)
          }else {
            uni.showToast({
              title: '更新失败,请稍后重试',
              icon: "none"
            });
          }
        })
      },
      // 删除分析报告
      delReport(eventId) { 
        this.$http({
          url: this.$api.analyze.delete,
          data: {
            eventId
          }
        }).then( res => {
          if(res.code == 0) {
            this.closePopup();
            this.list.splice(this.report_index,1);
            uni.showToast({
              title: '删除成功',
              icon: "success"
            });
          }else {
            uni.showToast({
              title: '删除失败',
              icon: "none"
            });
          }
        })
      },
      // 初始化请求
      initGetData() {
        this.page = 1;
        this.getData();
      },
      // 搜索
      confirmSearch() {
        if(this.keyWord == "") {
          uni.showToast({
              title: '请输入关键词',
              icon: "none"
          });
          return
        }
        this.initGetData();
      },
      // 点击更新报告
      updateReport(item,index) {
        let status = item.result[item.result.length-1].status
        if( status == 1 ) {
          uni.showToast({
              title: '报告分析中',
              icon: "none"
          });
          return
        }
        if( status == 0 ) {
          uni.showToast({
              title: '报告在等待分析',
              icon: "none"
          });
          return
        }
        this.event_id = item.parentEventId;
        this.report_index = index;
        this.picker_show = true;
        uni.hideTabBar()
      },
      // 点击查看分析
      lookAnalyze() {
        uni.navigateTo({
          url: '../analyze/analyzeDet/index'
        });
      },
      // 点击删除分析
      deleteAnalyze(id,title,index) {
        let self = this;
        uni.showModal({
          title: '提示',
          content: '确定删除['+title+']报告吗？',
          success(res) {
            if (res.confirm) {
              self.report_index = index;
              self.delReport(id)
            }
          }
        });
      },
      // 关闭弹窗
      closePopup() {
        this.$refs.analyze_popup.close();
      },
      // 关闭搜索
      closeSearch() {
        this.search_status = false;
      },
      // 确定选择日期
      confirmDate(e) {
        let today = new Date(new Date().toLocaleDateString()).getTime();
        let last_day = new Date(new Date(e.date[1]).toLocaleDateString()).getTime();
        if(today < last_day) {
          uni.showToast({
            title: '日期范围不能大于今天',
            icon: 'none'
          });
          return
        }
        this.date_arr = [];
        e.value.forEach(val => {
            let date = val.replace(/\//g, '-');
            date = date + " 00:00:00"
            this.date_arr.push(date)
        });
        this.updateAnalyze(this.date_arr)
        this.closePicker()
      },
      // 取消选择日期
      closePicker() {
        uni.showTabBar()
        this.picker_show = false
      }
    }
  }
</script>

<style lang="scss" scoped>
.analyze_page {
  width: 100%;
  box-sizing: border-box;
  transition: all .3s;
  .analyze_list {
    width: 100%;
    padding: 20upx 20upx 0;
    box-sizing: border-box;
    >view {
      margin-bottom: 20upx;
      &:nth-last-child(1) {
        margin: 0;
      }
    }
  }
  .hotList_set {
    .set_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-top: 0;
      .update_btn {
        width: 150upx;
        height: 100%;
        font-size: 30upx;
        color: #0084FF;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 500;
      }
    }
    .set_list {
      height: 70vh;
      padding: 20upx;
    }
    .del_btn {
      background: #F56C6C;
    }
  }
  .search_view {
    height: 0;
    overflow: hidden;
    position: fixed;
    left: 0;
    top: 0;
    /*  #ifdef  H5 */
    top: 88upx;
    /*  #endif  */
    z-index: 99;
    transition: all .3s;
  }
  .show_search {
    height: 88upx;
    border-bottom: 1px solid #eee;
    box-sizing: border-box;
  }
}
.top {
  padding-top: 88upx;
}
</style>